package by.grsu.samusev.dao.impl;

import java.io.Serializable;
import java.util.List;

import by.grsu.samusev.entity.Car;
import by.grsu.samusev.table.CarTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class CarDao extends AbstractDao<CarTable, Car>  {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6617629248600499281L;

	public CarDao(final String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public Long saveNew(final Car newCar) {
		Long nextId = getNextId();
		newCar.setId(nextId);
		final CarTable carTable = deserializeFromXml();
		carTable.getRows().add(newCar);
		serializeToXml(carTable);
		return nextId;
	}

	@Override
	public void update(final Car entity) {
		final CarTable carTable = deserializeFromXml();
		for (final Car row : carTable.getRows()) {
			if (row.getId().equals(entity.getId())) {
				row.setId(entity.getId());
				row.setCharacteristics(entity.getCharacteristics());
				row.setStatus(entity.getStatus());
				break;
			}
		}
		serializeToXml(carTable);

	}

	@Override
	public Car get(final Serializable id) {
		final CarTable carTable = deserializeFromXml();
		for (final Car row : carTable.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}

	@Override
	public List<Car> getAll() {
		final CarTable carTable = deserializeFromXml();
		return carTable.getRows();
	}

	@Override
	public void delete(final Serializable id) {
		final CarTable carTable = deserializeFromXml();
		Car toBeDeleted = null;
		for (final Car row : carTable.getRows()) {
			if (row.getId().equals(id)) {
				toBeDeleted = row;
				break;
			}
		}
		carTable.getRows().remove(toBeDeleted);
		serializeToXml(carTable);
	}

	@Override
	protected Class<CarTable> getTableClass() {
		return CarTable.class;
	}
}
